<?php

namespace app\index\service;

use app\common\model\ToolModel;
use app\index\model\UserModel;
use app\index\model\DatamanufactureModel;
use think\Cache;

class DatamanufactureService
{
    /**
     * 详情
     * @author LSH
     * @return array
     */
    public static function getSkuInfoDetailsLogic($param)
    {
        $title = '';
        $categorypath = '';
        $description = '';
        $productattr = '';
        $edit = ToolModel::find('manage_edit_audit',['id'=>$param['id']]);
        $data = DatamanufactureModel::dbGetSkuInfo($edit['sku']);
        $data['img'] = self::getSkuImg($edit['sku']);

        //分类
        $category = ToolModel::find('common_categories_path',['cate_id'=>$data['category_id']]);
        if(isset($category['cate_name_path'])){
            $categorypath = str_replace('|','->',$category['cate_name_path']);
        }
        $data['categorypath'] = $categorypath;

        if(empty($edit['assign_id'])){
            $oldedit = ToolModel::select('sku_multiple_attribute',['sku'=>$edit['sku']]);
            foreach ($oldedit as $value) {
                if($value['type'] == 1) $desc_template = $value['value_json'];
                if($value['type'] == 2) $title_template = $value['value_json'];
                if($value['type'] == 3) $smt_template = $value['value_json'];
            }

            $data['aslength'] = $data['taslength'];
            $data['aswide'] = $data['taswide'];
            $data['ashight'] = $data['tashight'];
        }else{
            $data['color'] = $edit['color'];
            $data['type'] = $edit['type']; 
            $data['shape'] = $edit['shape'];
            $data['size'] = $edit['size'];
            $data['pattern'] = $edit['pattern'];
            $data['audit_status'] = $edit['audit_status'];

            $data['balelength'] = $data['aslength'];
            $data['balewide'] = $data['aswide'];
            $data['balehight'] = $data['ashight'];
            
            $title_template = $edit['title_template'];
            $desc_template = $edit['desc_template'];
            $smt_template = $edit['smt_template'];
        }
        //标题
        if(isset($title_template)){
            $titleArr = json_decode($title_template,TRUE);
            if(isset($titleArr['value']) && is_array($titleArr['value'])){
                foreach ($titleArr['value'] as $val) {
                    $title .= str_replace('卍','、',$val).' ';
                }
            }
        }
        $data['title'] = $title;

        //描述
        if(isset($desc_template)){
            $descArr = json_decode($desc_template,TRUE);
            if(is_array($descArr)){
                foreach ($descArr as $key => $val) {
                    $description .= '<b style="font-size:15px">'.$key.'</b>：<br/>'.$val.'<br/><br/>';
                }
            }
        }
        $data['description'] = $description;

        // 产品属性 / 速卖通属性
        if(isset($smt_template)){
            $smtArr = json_decode($smt_template,TRUE);
            if(is_array($smtArr['smtKeyValue'])){
                foreach ($smtArr['smtKeyValue'] as $key => $val) {
                    $productattr .= '<b style="font-size:15px">'.$key.'</b>：'.str_replace('卍','、',$val).'<br/>';
                }
            }
        }
        $data['productattr'] = $productattr;

        return returnArr(1,'',$data);
    }
    
    public static function getSkuImg($sku)
    {
        $cache=Cache::get('getSkuImg'.$sku);
        if ($cache) {
            return $cache;
        }
        $url = "http://skuimg.kokoerp.com/api/?c=api_pictureurl_urlservers&a=get_pictureurl";
        $data = ["sku"=>trim($sku),"gallery_id"=>1,"type"=>null,"all_type"=>false,"url_type"=>'https'];
        $result = curl($url, $data,'','POST',10,false);
        $result = json_decode($result,TRUE);
        if(isset($result[$sku])&&$result[$sku]){
            $img = [];
            foreach($result[$sku] AS $vl){
                foreach($vl AS $v){
                    foreach($v AS $vv){
                        $imageurl=explode('://',$vv);
                        $imageurl='http://s3cdn.kokoerp.com/file/'.$imageurl[1];
                        $img[] = $imageurl;
                    }
                }
            }
            Cache::set('getSkuImg'.$sku,$img,259200);//缓存3天
            return $img;
        }
        return $result;
    }

    public static function getSkuImgBatch($skus)
    {   
        if(!is_array($skus) || empty($skus)){
            return [];
        }

        $url = "192.168.5.207:9991/data/tuku/batchQuery";
        $list = [];
        foreach ($skus as $k => $sku) {
            $list[$k]['sku'] = $sku;
            $list[$k]['tuku'] = 1;
            $list[$k]['type'] = null;
        }
        $params['skuList'] = json_encode($list);

        $result = curl($url, $params,'','POST',3,false);
        $result = json_decode($result,TRUE);
        $img = [];

        if(!empty($result) && is_array($result)){
            foreach($result AS $imgarr){
                foreach($imgarr AS $k => $v){
                    $sku = substr($k,0,-2);
                    foreach($v AS $imageurl){
                        $img[$sku]['img'][] = 'http://'.$imageurl;
                        $name1 = substr($imageurl,strrpos($imageurl, '/')+1);
                        $name2 = substr($name1,0,strpos($name1, '.'));
                        $img[$sku]['name'][] = $name2;
                    }
                }
            }
        }
        
        return $img;
    }

    /**
     * 资料制作列表/导出
     * @author LSH
     * @return array
     */
    public static function getDataManufactureList($param){

        $titles = [
            'sku'=>'SKU',
            'spu'=>'SPU',
            'name'=>'采购名称',
            'creation_time'=>'交接时间',
            'developer'=>'开发人员',
            'imitation'=>'仿品（具体品牌）',
            'realpic'=>'盗图/实拍图',
            'logo'=>'品牌Logo',
            'quantity'=>'销售数量/单位',
            'develop_link'=>'开发链接',
            'research_links'=>'调研链接',
            'handover_type'=>'交接类型',
            'authorization_name'=>'是否授权',
            'aslengthaswideashight'=>'打包前尺寸',
            'handover_remarks'=>'交接备注',
            'audit_type'=>'制作类型',
        ];

        if($param['type'] == 'img'){
            $titles['grade'] = '图片等级';
            $titles['operator'] = '图片人员';
        }else{
            $titles['grade'] = '描述等级';
            $titles['operator'] = '编辑人员';
        }

        $titles['assign_time'] = '分派时间';
        $titles['finish_time'] = '完成时间';
        $titles['mstatus_name'] = '制作状态';
        $titles['status_name'] = '审核状态';
        $titles['audit_remarks'] = '审核备注';

        return DatamanufactureModel::dbGetDataManufactureList($param, $titles, "\app\index\service\DatamanufactureService::getDataManufactureListLogic");
    }

    /**
     * 资料制作
     * @author LSH
     * @return array
     */
    public static function getDataManufactureListLogic($data)
    {
        $skus = array_column($data, 'sku');
        $attribute = ToolModel::select('sku_attribute',['sku'=>['IN',$skus]], 'sku_attribute.*,CASE authorization WHEN 0 THEN "未授权" WHEN 1 THEN "已授权" ELSE "" END authorization_name','','sku');
        $maudit = ToolModel::select('manage_manufacture_audit',['sku'=>['IN',$skus]], 'CASE type WHEN 1 THEN "资料包" WHEN 2 THEN "样品" ELSE "" END audit_type, CASE status WHEN 1 THEN "待审核" WHEN 2 THEN "已审核" WHEN 3 THEN "已驳回" ELSE "" END status_name','','sku');

        $proposer = array_column($data, 'proposer'); //申请人员
        $operator = array_column($data, 'operator'); //图片/编辑人员
        $developer = array_column($attribute, 'developer'); //开发人员
        $user_id = array_filter(array_merge($proposer,$operator,$developer));
        $user = UserModel::getUserById($user_id);

        foreach ($data as &$val) {
            $attr = $attribute[$val['sku']]??[];
            $val['audit_type'] = isset($maudit[$val['sku']])?$maudit[$val['sku']]['audit_type']:'';
            $val['status_name'] = isset($maudit[$val['sku']])?$maudit[$val['sku']]['status_name']:'';
            
            if(!empty($val['assign_id'])){
                //新品
                $val['proposer'] = $user[$attr['developer']]??'';
                $val['logo'] = $val['hlogo']??'';
                $val['quantity'] = $val['hquantity'].$val['hquantity_unit'];
                $val['aslengthaswideashight'] = $val['aslength'].'*'.$val['aswide'].'*'.$val['ashight'];
            }else{
                //老品
                $val['proposer'] = $user[$val['proposer']]??'';
                $val['logo'] = $attr['logo']??'';
                $val['imitation'] = $attr['imitation']??'';
                $val['realpic'] = $attr['realpic']??'';
                $val['research_links'] = $attr['research_links']??'';
                $val['authorization_name'] = $attr['authorization_name']??'';
                $val['quantity'] = $attr['quantity'].$attr['quantity_unit'];
                $val['aslengthaswideashight'] = $attr['aslength'].'*'.$attr['aswide'].'*'.$attr['ashight'];
                if($val['ttype'] == 'img') $val['handover_type'] = $val['manufacture_type']??'';
            }


            $val['develop_link'] = $attr['develop_link']??'';
            $val['developer'] = $user[$attr['developer']]??'';
            $val['operator'] = $user[$val['operator']]??'';
            $val['audit_type'] = empty($val['audit_type'])?$val['manufacture_type']:$val['audit_type'];
            $val['skuinfo'] = 'SKU：'.$val['sku'].'<br/>SPU：'.$val['spu'].'<br/>采购名称：'.$val['name'];
            $val['timeinfo'] = '分派时间：'.$val['assign_time'].'<br/>完成时间：'.$val['finish_time'];
            $val['imgmaterialinfo'] = '销售数量/单位：'.$val['quantity'].'<br/>品牌Logo：'.$val['logo'];
            $val['imgmanufactureinfo'] = '制作类型：'.$val['audit_type'].'<br/>图片等级：'.$val['grade'].'<br/>交接类型：'.$val['handover_type'];
            $val['imgpersonalinfo'] = '申请人员：'.$val['proposer'].'<br/>图片人员：'.$val['operator'];
            $val['editmaterialinfo'] = '制作类别：'.$val['product_type'].'<br/>描述等级：'.$val['grade'];
            $val['editmanufactureinfo'] = '制作类型：'.$val['audit_type'].'<br/>交接类型：'.$val['handover_type'];
            $val['editpersonalinfo'] = '申请人员：'.$val['proposer'].'<br/>编辑人员：'.$val['operator'];
        }
        
        return $data;
    }

    /**
     * 资料制作批量提交
     * @author LSH
     * @return array
     */
    public static function uploadImgSubmitInfo($datas, $param)
    {
        $skus = ['new'=>[],'old'=>[]];
        $error = [];
        $exist = ToolModel::select('manage_img_audit', ['manufacture_status'=>['IN',[2,4]]], 'sku,assign_id','','sku');

        foreach ($datas as $k => $v) {
            if(!isset($exist[$v[0]])){
                $error[] = "SKU: {$v[0]} 已提交，请核实后重新导入。";
                continue;
            }

            $type = ($exist[$v[0]] == 0)?'old':'new';
            $skus[$type][] = $v[0];
        }

        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            unset($error);
            return returnArr(2, '',$msg);
        }else{
            $time = date('Y-m-d H:i:s',time());
            $data = ['audit_status'=>1,'finish_time'=>$time];
            $where = ['manufacture_status'=>['IN',[2,4]]];
            if(count($skus['new'])){
                $data['manufacture_status'] = 3;
                $where['sku'] = ['IN',$skus['new']];
                ToolModel::updateData($where,$data, 'manage_img_audit');
                ToolModel::updateData(['sku'=>['IN',$skus['new']]],['status'=>4], 'sku_handover');
            }
            
            if(count($skus['old'])){
                $data['manufacture_status'] = 5;
                $where['sku'] = ['IN',$skus['old']];
                ToolModel::updateData($where,$data, 'manage_img_audit');
            }
            
            unset($skus,$datas,$param);
        }

        //成功
        return returnArr();
    }

    /**
     * 制作提交状态更改
     * @author LSH
     * @return array
     */
    public static function updateManufactureStatusLogic($param)
    {
        $exist = ToolModel::select('manage_img_audit', ['sku'=>$param['sku'],'manufacture_status'=>['IN',[2,4]]], 'sku,assign_id','','sku');
        if(!isset($exist[$param['sku']]))
            return returnJson(0,'该数据不能存在或已提交！');

        $param['assignid'] = $exist[$param['sku']];
        return DatamanufactureModel::dbUpdateManufactureStatus($param);
    }
}